import CaseApi from '../../api/case.api'
import UserApi from '../../api/user.api'
import HTTP from '../../services/api';
import UserCard from '../../component/reserve/userCard';
import SlefUpload from '../../tools/Upload'
import { Row, Col, Button, message, notification, Modal, Form, Input, Divider, Select, InputNumber,Result,Avatar } from 'antd';
import SelfTable from '../../tools/selfTable'
import { CheckCircleOutlined, CloseOutlined } from '@ant-design/icons'
import React from 'react';
import { history } from 'umi';
import drugApi from '../../api/drug.api';
const { TextArea, Search } = Input;
const { Option } = Select;






export default class EditReserve extends React.Component {
    constructor() {
        super()
        this.state = {
            studentInfo: {},
            student_id: '',
            register_id: '',
            isModalVisible: true,
            isloading: false,
            drugInfo: [],
            prescription: [],
            isadddrug: false,
            usedrug: {},
            prescriptionId: '',
            caseId: ''

        }
    }

    getStudentInfoById = async () => {
        let { student_id } = this.state
        let result = await HTTP({ method: 'get', id: student_id }, UserApi.getStudentInfoById)
        console.log(result)
        try {
            if (result.status) {
                message.success(result.msg)
                this.setState({ studentInfo: result.info })
            }
            else {
                message.error(result.msg)
            }
        } catch (e) {
            message.error('服务器异常')
        }
    }

    getReserveId = id => {
        // todo
    }
    // prescription_id
    // register_id
    // student_id
    // worker_id
    CreateCaseByStudentId = async () => {
        let { student_id, studentInfo } = this.state
        let result = await HTTP({ method: 'get' }, CaseApi.createCaseByStudentid, { student: student_id })
        try {
            if (result.status) {
                this.setState({ prescriptionId: result.prescriptionId, caseId: result.caseId })
                notification.success({
                    message: '成功',
                    description:
                        `为${studentInfo.username}学生创建病例成功`
                })
            } else {
                message.error(result.msg)
            }
        } catch (err) {
            message.error('服务器异常')
        }
    }
    componentDidMount() {
        this.getDrugInfoByname()
        let { registerid, studentid } = history.location.query
        if (registerid && studentid) {
            this.setState({ register_id: registerid, student_id: studentid }, () => {
                this.getStudentInfoById()
            })
        } else {
            message.error('没有发现学生的信息,跳转回页面')
            history.push('/reserve')
        }

    }
    // 确认的回调
    handleOk = async () => {
        this.setState({ loading: true })
        await this.CreateCaseByStudentId()
        this.setState({ loading: false })
        this.setState({ isModalVisible: false })


    }
    // 取消的回调
    handleCancel = () => {
        console.log('no')
    }

    getDrugInfoByname = async (drugname) => {
        let result = await HTTP({ method: 'get' }, drugApi.getDrugInfoByname, { drugname })
        console.log(result)
        try {
            if (result.status) {
                this.setState({ drugInfo: result.info })
                notification.success({
                    message: '成功',
                    description:
                        `查询出${result.info.length}条药品信息`
                })
            } else {
                // message.error(result.msg)
            }
        } catch (err) {
            message.error("服务器异常")
        }
    }

    onSearch = drugname => {
        console.log(drugname)
        if (drugname) {
            this.getDrugInfoByname(drugname)
        }
    }

    onFinish = () => {
        this.setState({ isadddrug: false })
    }

    addDrug = valueObj => {
        // todo
        let { usedrug, prescriptionId, prescription } = this.state
        console.log(usedrug)
        console.log('-------------------')
        const newUseDrug = { ...valueObj, ...usedrug, prescription_id: prescriptionId }
        newUseDrug.price = newUseDrug.price * newUseDrug.usecount;
        this.setState({ prescription: [...prescription, newUseDrug] }, () => { console.log(this.state.prescription) })

        this.onFinish()

    }
    onChange = (value) => {
        let { drugInfo } = this.state
        this.setState({ usedrug: drugInfo.find(element => element['drug_id'] == value) })
        console.log(drugInfo.find(element => element['drug_id'] == value))
        this.setState({ isadddrug: true })
    }

    submit = async value => {
        let { student_id, caseId, prescriptionId, prescription } = this.state
        console.log(value)
        value = { ...value, prescriptions: prescriptionId }
        let data = {}
        data['case'] = value
        data['rescription'] = prescription
        data['prescription_id'] = caseId
        console.log(data)
        let result = await HTTP({ method: 'put', id: caseId }, CaseApi.caseRestfu, data)
        try {
            if (result.status) {
                message.success(result.msg)
            } else {
                message.error(result.msg)
            }
        } catch (error) {
            message.error('服务器异常')
        }

    }
    render() {
        let { studentInfo, isModalVisible, isloading, prescription, drugInfo, isadddrug, usedrug } = this.state
        const columns = [

            {
                title: '药品的名称',
                dataIndex: 'drug_name',
            },
            {
                title: '使用量',
                dataIndex: 'usecount',
            },
            {
                title: '药品的id',
                dataIndex: 'drug_id',
            },
            {
                title: '总价格',
                dataIndex: 'price',
            },
            {
                title: '备注',
                dataIndex: 'comment',
            }
        ]
        const Idrug = [
            {
                key: 'comment',
                value: '备注'
            },
            {
                key: 'count',
                value: '剩余数量'
            },
            {
                key: 'createdAt',
                value: '创建时间'
            },
            {
                key: 'drug_id',
                value: '药品ID'
            },
            {
                key: 'drug_name',
                value: '药品名称'
            },
            {
                key: 'price',
                value: '药品价格'
            },
            {
                key: 'specification',
                value: '计量单位'
            },
            {
                key: 'unit',
                value: '规格'
            },
            {
                key: 'updatedAt',
                value: '更新时间'
            }

        ]
        const options = drugInfo.map(d => <Option key={d.drug_id}>{d.drug_name}</Option>);
        return (
            <div>
                <Result
                style={{height:'200px',padding:'20px 32px'}}
                    status="success"
                    icon={<Avatar size={98} src='/logo.svg' />}
                    title="XXX学校校医院病例系统"
                    // subTitle="Order number: 2017182818828182881 Cloud server configuration takes 1-5 minutes, please wait."
                />
                <Modal
                    maskClosable={false}
                    title='确认学生信息'
                    width='50%'

                    cancelText={<p>取消看病&nbsp;&nbsp;&nbsp;<CloseOutlined /></p>}
                    okText={<p>为其创建病例&nbsp;&nbsp;&nbsp;<CheckCircleOutlined /></p>}
                    onOk={this.handleOk} onCancel={this.handleCancel}
                    onCancel={() => { this.setState({ isModalVisible: false }) }}
                    visible={isModalVisible}
                >
                    <UserCard userinfo={studentInfo}></UserCard>
                </Modal>
                <Modal
                    title='确认药品信息'
                    width='25%'
                    okText={<p>增加此药品&nbsp;&nbsp;&nbsp;<CheckCircleOutlined /></p>}
                    // onOk={value=>this.addDrug(value)}
                    onCancel={this.handleCancel}
                    visible={isadddrug}>
                    <Row justify='center' align='middle'>
                        <Form
                            onFinish={value => { this.addDrug(value) }}
                        >
                            {
                                Idrug.map(item =>
                                    <Col span={24}>
                                        <Form.Item
                                            style={{ width: '100%' }}
                                            label={item.value}
                                            name={item.key}
                                            rules={[{ required: false, message: '' }]}
                                        >
                                            <Input style={{ width: '100%' }} disabled defaultValue={usedrug[item.key]} />
                                        </Form.Item>
                                    </Col>)
                            }
                            <Col span={24}>
                                <Form.Item
                                    style={{ width: '100%' }}
                                    label='数量'
                                    name='usecount'
                                    rules={[{ required: false, message: '请输入需要开出的药品数量!' }]}
                                >
                                    <InputNumber style={{ width: '100%' }} max={10} min={1} />
                                </Form.Item>
                            </Col>
                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>
                        </Form>
                    </Row>
                </Modal>
                <UserCard userinfo={studentInfo}></UserCard>

                <Form
                    style={{ padding: '5px 20px' }}
                    name="basic"
                    // labelCol={{ span: 8 }}
                    // wrapperCol={{ span: 16 }}
                    initialValues={{ remember: true }}
                    onFinish={value => { this.submit(value) }}
                // onFinishFailed={onFinishFailed}
                >
                    <Divider orientation="left" plain>学生的体征</Divider>
                    <Row>
                        <Col span={6}>
                            <Form.Item
                                label="体温"
                                name="temperature"
                                rules={[{ required: true, message: '请输入学生的 体温!' }]}
                            >
                                <Input />
                            </Form.Item>
                        </Col>
                        <Col span={6}>
                            <Form.Item
                                label="脉搏"
                                name="pulse"
                                rules={[{ required: true, message: '请输入学生的 脉搏!' }]}
                            >
                                <Input />
                            </Form.Item>
                        </Col>
                        <Col span={6}>
                            <Form.Item
                                label="呼吸"
                                name="breathing"
                                rules={[{ required: true, message: '请输入学生的 呼吸!' }]}
                            >
                                <Input />
                            </Form.Item>
                        </Col>
                        <Col span={6}>
                            <Form.Item
                                label="血压"
                                name="blood_pressure"
                                rules={[{ required: true, message: '请输入学生的 血压!' }]}
                            >
                                <Input />
                            </Form.Item>
                        </Col>

                    </Row>
                    <Divider orientation="left" plain>医生的描述</Divider>
                    <Row>
                        <Col span='24'>
                            <Form.Item
                                label="体格评价"
                                name="physical_evaluation"
                                rules={[{ required: true, message: '请输入学生的 体格评价!' }]}
                            >
                                <TextArea autoSize showCount maxLength={1000} />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Divider orientation="left" plain>医生的描述</Divider>
                    <Row>
                        <Col span='24'>
                            <Form.Item
                                label="目前的情况"
                                name="bigintr"
                                rules={[{ required: true, message: '请输入学生的目前情况!' }]}
                            >
                                <TextArea autoSize showCount maxLength={1000} />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row>
                        <Col span='24'>
                            <Form.Item
                                label="检查结果"
                                name="examination_result"
                                rules={[{ required: true, message: '请输入学生的 检查结果!' }]}
                            >
                                <TextArea autoSize showCount maxLength={1000} />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Divider orientation="left" plain>医生的处方</Divider>

                    <Row>
                        <Col span='24'>
                            {/* <Search */}

                            <Select placeholder='输入药品的名称'
                                style={{ width: '100%' }}
                                showSearch
                                onChange={value => { this.onChange(value) }}
                                onSearch={value => { this.onSearch(value) }}

                            >
                                {
                                    options
                                }
                            </Select>
                        </Col>
                    </Row>
                    <Row>
                        <Col span='24'>
                            <SelfTable columns={columns} dataSource={prescription} keyid='drug_id' />
                        </Col>
                    </Row>
                    <Divider orientation="left" plain>回执</Divider>
                    <Row>
                        <Col span='24'>
                            <Form.Item
                                label="回执"
                                name="receipt"
                                rules={[{ required: false, message: '请输入学生的回执!' }]}
                            >
                                <TextArea autoSize showCount maxLength={1000} />
                            </Form.Item>
                        </Col>
                    </Row>
                    {/* <Divider orientation="left" plain>外出的病例</Divider>
                    <Row>
                        <Col span='24'>
                            <Form.Item
                                label="外出的病例"
                                name="case_out"
                                rules={[{ required: false, message: '请输入学生的回执!' }]}
                            >
                                <TextArea autoSize showCount maxLength={1000} />
                            </Form.Item>
                            <SlefUpload/>
                        </Col>
                    </Row> */}
                    <Row>
                        <Col>
                            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                                <Button type="primary" htmlType="submit">
                                    提交
                                </Button>
                            </Form.Item>
                        </Col>
                    </Row>

                </Form>
            </div>
        );
    }

}

// examination_result	
// [string]	是	检查的结果		
// prescriptions	
// [object]	是	处方的id		

// physical_evaluation	
// [string]	是	体格评价				
// case_out复制
// [string]	是	外出治疗的病例


    //   placeholder="输入药品名称"
    //   allowClear
    //   enterButton="Search"
    //   size="large"
    //   onChange={value =>{this.onSearch(value)}}
    //   onSearch={value =>{this.onSearch(value)}}
    // >